package www.ld.com.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import www.ld.com.handler.AuthExceptionEntryPoint;
import www.ld.com.handler.CustomAccessDeniedHandler;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableResourceServer
public class ResourceServerAutoConfiguration extends ResourceServerConfigurerAdapter {
    @Value("${spring.application.name}")
    private String resource_id;
    @Resource
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint());
        resources.accessDeniedHandler(new CustomAccessDeniedHandler());
        resources.tokenStore(tokenStore).resourceId(resource_id);
    }




    @Override
    public void configure(HttpSecurity http) throws Exception {
        List<String> permitAllResouces = new ArrayList<>();
        //Swagger资源
        permitAllResouces.addAll(Arrays.asList("/oauth/**", "api/**", "/personal/oauth/**", "/auth/**", "/v2/**", "/swagger-resources", "/swagger-resources/**"));
        String[] resouceArray = permitAllResouces.toArray(new String[]{});
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)//禁用 HttpSession
                .and().authorizeRequests().mvcMatchers(resouceArray).permitAll();
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }


}
